package com.hp.springboot.service;

import com.hp.springboot.dao.TGoodDao;
import com.hp.springboot.dao.TUserDao;
import com.hp.springboot.pojo.model.TGood;
import com.hp.springboot.pojo.model.TUser;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Service 和 Mapper 混合的事务模式测试
 * 结论：
 * Spring事务的本质是在数据源中对事务进行手动提交；所以，在同一个数据源内，跟程序的写法无关
 * 无论是写在Service中还是DAO中，本质都是操作当前数据源，本质相同。
 * 不管怎么写，Spring最终是：在语句前面开启事务，在语句后面提交事务，遇到异常回滚。
 *
 * @author hupan
 * @date 2022-01-12 23:31
 */
@Slf4j
@Service
public class MixTransactionalService {

    @Resource
    private TUserDao tUserDao;
    @Resource
    private TUserService tUserService;
    @Resource
    private TGoodDao tGoodDao;
    @Resource
    private TGoodService tGoodService;

    /**
     * 同一个Model的 Service + DAO 结果：事务有效
     */
    @Transactional(rollbackFor = Exception.class)
    public void test1() {
        TUser user = new TUser();
        user.setName("TestUser1");
        user.setPhone("18922334411");
        user.setPassword("123456");
        tUserService.save(user);

        tUserDao.insert(new TUser());
    }

    /**
     * 同一个Model的Service调用两次 结果：事务有效
     */
    @Transactional(rollbackFor = Exception.class)
    public void test2() {
        TUser user = new TUser();
        user.setName("TestUser1");
        user.setPhone("18922334411");
        user.setPassword("123456");
        tUserService.save(user);

        tUserService.save(new TUser());
    }

    /**
     * 不同Model的不同Service
     */
    @Transactional(rollbackFor = Exception.class)
    public void test3() {
        TGood good = new TGood();
        good.setGoodCode("10000");
        good.setGoodName("banana");
        tGoodService.insert(good);

        tUserService.save(new TUser());
    }

    /**
     * 不同Model的Service和DAO
     */
    @Transactional(rollbackFor = Exception.class)
    public void test4() {
        TGood good = new TGood();
        good.setGoodCode("10000");
        good.setGoodName("banana");
        tGoodDao.insert(good);

        tUserService.save(new TUser());
    }


}
